package org.cnc.machine;

import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import org.cnc.core.MachineControl;
import org.cnc.core.MachineControl.Command;

public class CncMachine extends Thread {
	
	private MachineControl controller;
	private CncCutter cutter;
	private ChangeListener listener;
	
	public CncMachine ( MachineControl ctrl )
	{
		controller = ctrl;
		cutter = new CncCutter();
	}
	
	public void addChangeListener(ChangeListener l)
	{
		listener = l;
	}
	
	public CncCutter getCutter()
	{
		return cutter;
	}
	
	private void doStep( MachineControl.Command command )
	{
		cutter.move( command );

		ChangeEvent e = new ChangeEvent(command);		

		System.out.println("Machine: x:"+cutter.getPosition().x()+" y:" + cutter.getPosition().y() + " z: " + cutter.getPosition().z());
		
		listener.stateChanged(e);		
	}
	
	public CutterPosition getCutterPosition()
	{
		return cutter.getPosition();
	}
	
	@Override
	public void run() {

		MachineControl.Command command;
		
		CutterPosition pos = controller.getInitCutterPosition();
		
		if ( pos != null )
		{
			cutter.setPosition(pos.x(), pos.y(), pos.z());
		}
		
		while ( ( command = controller.getNextStep() ) != MachineControl.Command.STOP )
		{
			int delay = controller.getDelayTime();
			
			try {
				if ( command != Command.WAIT)
					doStep(command);
				sleep( delay );
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		doStep(Command.STOP);
	}	
}
